<script setup>
import { ref } from "vue";
import { userQueryPasswordById, userUpdateUserPasswordById } from "@/api/user";
import { ElMessage } from 'element-plus'
const fromValues = ref({
  oldPassword: "",
  newPassword: "",
  confirmNewPassword: "",
})
const getOldPassword = async () => {
  const { result } = await userQueryPasswordById()
  fromValues.value.oldPassword = result.password
}
getOldPassword()

const rules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' }
  ],
  confirmNewPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== fromValues.value.newPassword) {
          callback('两次输入的密码不一致')
        } else {
          callback()
        }
      }
      , trigger: 'blur'
    },

  ]
}

const formRef = ref(null)

const onSubmit = async () => {
  // 再次触发校验
  formRef.value.validate(async (valid) => {
    if (valid) {
      await userUpdateUserPasswordById({ password: fromValues.value.newPassword })
      ElMessage.success('修改密码成功')
    } else {
      ElMessage.error('请检查输入')
    }
  })
}

</script>

<template>
  <div class="change-password">
    <el-text type="primary">
      <h1>修改密码</h1>
    </el-text>
    <el-form label-width="auto" :model="fromValues" :rules="rules" ref="formRef">
      <el-form-item label="旧密码">
        <el-input v-model="fromValues.oldPassword" disabled></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="fromValues.newPassword"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmNewPassword">
        <el-input v-model="fromValues.confirmNewPassword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="$router.back()">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.change-password {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 20px;
  height: 100vh;
}

.el-input {
  width: 50vw;
}
</style>
